package model.data.database;

import java.util.ArrayList;
import java.util.List;

import model.Product;
import model.data.ProductStore;

public class ProductTable implements ProductStore {
	/* Handles requests to the database */
	DatabaseHandler dbHandler;
	
	/** Constructs a new category table */
	public ProductTable() {
		this.dbHandler = new DatabaseHandler();
	}
	@Override
	public void write(Product product) throws Exception {
		this.dbHandler.callUpdateProcedure("sp_insertproduct(?,?,?)", product.getName(), product.getPrice(), product.getId());
	}

	@Override
	public void update(Product product) {
		// TODO Auto-generated method stub
	}

	@Override
	public void delete(Product product) throws Exception {
		this.dbHandler.callUpdateProcedure("sp_deletecategory(?)", product.getId());
	}

	@Override
	public int getCount() throws Exception {
		int count = 0;
		ArrayList<DataRecord> records;

		// Get records
		records = (ArrayList<DataRecord>)this.dbHandler.callQueryProcedure("sp_getcountproduct");
		
		// Fill list
		for (DataRecord dr : records) {
			count = Integer.parseInt(dr.getValue("Result"));
		}
		
		// Return result
		return count;
	}

	@Override
	public List<Product> getById(long id) throws Exception {
		ArrayList<Product> products;
		ArrayList<DataRecord> records;
		
		// Get records
		records = (ArrayList<DataRecord>)this.dbHandler.callQueryProcedure("sp_getbyidproduct(?)", id);
		
		// Create list
		products = new ArrayList<Product>();
		
		// Fill list
		//TODO
		for (DataRecord dr : records) {
			Product product = new Product();
			product.setId(Long.parseLong(dr.getValue("ProductID")));
			product.setCategory(Long.parseLong(dr.getValue("CategoryID")));
			product.setName(dr.getValue("Name"));
			product.setPrice(Float.parseFloat("Price"));
			products.add(product);
		}
		
		// Return result
		return products;
	}
}
